import OSS from 'ali-oss';

let ossClient = null;
const config = {
  accessKeyId: 'LTAI5t9q43XZjiXZbifd1xQK',
  accessKeySecret: 'f9JBCe5osJmqghke4ArqncXvSeykjt',
};

export const initOSSClient = config => {
  ossClient = new OSS({
    region: 'oss-cn-hangzhou',
    accessKeyId: config.accessKeyId,
    accessKeySecret: config.accessKeySecret,
    bucket: 'xjj-test-oss',
    endpoint: 'oss-cn-hangzhou.aliyuncs.com'
  });
};

export const listFiles = async (prefix = '') => {
  try {
    const result = await ossClient.list({
      prefix,
      delimiter: '/',
    });
    return {
      directories: result.prefixes || [],
      files: result.objects || [],
    };
  } catch (error) {
    console.error('List files error:', error);
    throw error;
  }
};

export const getFileContent = async path => {
  try {
    const result = await ossClient.get(path);
    return result.content.toString();
  } catch (error) {
    console.error('Get file content error:', error);
    throw error;
  }
};

export const uploadFile = async (path, content) => {
  try {
    await ossClient.put(path, Buffer.from(content));
  } catch (error) {
    console.error('Upload file error:', error);
    throw error;
  }
};

export const deleteFile = async path => {
  try {
    await ossClient.delete(path);
  } catch (error) {
    console.error('Delete file error:', error);
    throw error;
  }
};
